<?php
namespace app\rabbitmq\producer;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitMQProducer
{
    protected static ?self $instance = null;
    protected $connection;
    protected $channel;

    public static function getInstance(): self
    {
        if (!self::$instance) {
            $config = config('plugin.rabbitmq.config');
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    public function __construct(array $config)
    {
        $this->connection = new AMQPStreamConnection(
            $config['host'],
            $config['port'],
            $config['user'],
            $config['password'],
            $config['vhost']
        );
        $this->channel = $this->connection->channel();
    }

    /**
     * 发送消息到指定队列
     */
    public function publish(string $queue, array $data)
    {
        $this->channel->queue_declare($queue, false, true, false, false);
        $messageId = uniqid('msg_', true); // 投递时生成唯一ID
        $msg = new AMQPMessage(json_encode($data, JSON_UNESCAPED_UNICODE), [
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            'message_id' => $messageId,
        ]);
        $this->channel->basic_publish($msg, '', $queue);
        echo "[x] Sent to {$queue}: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n";
        return $messageId;
    }

    public function __destruct()
    {
        $this->channel->close();
        $this->connection->close();
    }
}